import axios from "axios";
import router from "@/router";

const service = axios.create({
  baseURL: "/api",
  timeout: 100000000000,
});

service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["token"] = `${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    if (response.data.code === 401) {
      localStorage.removeItem("token");
      setTimeout(() => {
        message.warning("鉴权失效，即将返回登录页");
        router?.push("/login");
      }, 1500);
    }
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default service;
